class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int n = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        for (int i = 0; i < n - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < n - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                for (int k = j + 1; k < n - 1; k++) {
                    if (k > j + 1 && nums[k] == nums[k - 1]) continue;
                    int target0 = -nums[i] - nums[j] - nums[k] + target;
                    int l = k + 1, r = n - 1;
                    while (l <= r) {
                        int mid = (l + r) >> 1;
                        if (nums[mid] > target0) {
                            r = mid - 1;
                        } else if (nums[mid] < target0) {
                            l = mid + 1;
                        } else {
                            ans.add(Arrays.asList(nums[i], nums[j], nums[k], target0));
                            break;
                        }
                    }
                }
            }
        }
        return ans;
    }
}